const express = require('express');
const app = express();
const { User, Advice, ServiceOrder, Admin } = require('./db');
const { createSuperAdmin } = require('./create_super_admin');
const { v4 } = require('uuid');
const multer = require('multer');
const moment = require('moment')
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static(__dirname));

app.all('*', (req, res, next) => {
    // 允许所有源访问（生产环境应指定具体源）
    res.header('Access-Control-Allow-Origin', '*');
    // 允许的HTTP方法
    res.header('Access-Control-Allow-Methods', '*');
    // 允许的头部字段
    res.header('Access-Control-Allow-Headers', '*');
    next();
});

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, './file');
    },
    filename: (req, file, cb) => {
        const type = file.originalname.replace(/.+\./, '.');

        cb(null, `${v4()}${type}`);
    }
})

const upload = multer({ storage })

async function generateOrderNo() {
    // 获取当前时间戳的后几位（确保不重复） 
    const timestampPart = Date.now().toString().slice(-5);
    // 生成随机数填补剩余位数
    const randomPart = Math.floor(Math.random() * 10000000).toString().padStart(7, '0');
    // 组合成12位数字
    const uniqueId = (timestampPart + randomPart).slice(0, 12);
    return uniqueId;

}


module.exports = { generateOrderNo };

// 用户注册
app.post('/register', async (req, res) => {
    try {
        const { role, name, mobile, username, password } = req.body;
        // 判断当前账号是否已被注册
        const checkRes = await User.findOne({ username });
        if (checkRes) {
            res.send({
                msg: "registered"
            })
        } else {
            // 注册账号
            await User.create({
                user_id: v4(),
                role,
                name,
                mobile,
                username,
                password,
                create_time: new Date().getTime()
            });
            res.send({
                msg: "success"
            })
        }

    } catch (error) {
        // 注册过程出现错误
        console.log(error);
        res.send({
            msg: "error"
        })
    }
})

// 用户登录
app.post('/login', async (req, res) => {
    try {
        const { role, username, password } = req.body;
        const result = await User.findOne({
            role,
            username,
            password
        });
        if (result) {
            res.send({
                msg: "success",
                result,
            })
        } else {
            res.send({
                msg: "accountError"
            })
        }


    } catch (error) {
        console.log(error);
        res.send({
            msg: "error"
        })
    }
})

// 新增意见反馈
app.post('/add_advice', async (req, res) => {

    try {
        const { user_id, user_info, name, mobile, content, role, order_id} = req.body;
        if (!order_id) {
            res.send("order_id参数异常！")
            return
        }


        const oid = await Advice.find({ user_id:user_id,order_id: order_id,role:role})
        if (oid.length > 0) {
            res.send({
                code: 1007,
                msg: '当前反馈已存在,请勿重复提交'
            })
            return
        }
        await Advice.create({
            user_id,
            user_info,
            name,
            mobile,
            content,
            create_time: new Date().getTime(),
            status: 0,
            role,
            order_id
        });
        res.send("success");
    } catch (error) {
        console.log(error);
        res.send("error");
    }
});

// 查询用户的意见反馈历史
app.post('/get_advice_list', async (req, res) => {
    try {
        const { user_id, selectTab } = req.body;
        let params = {
            user_id
        }
        if (selectTab === 0) {

        } else if (selectTab === 1) {
            params['status'] = 0;
        } else if (selectTab === 2) {
            params['status'] = 1;
        }
        const result = await Advice.find(params);
        res.send(result);
    } catch (error) {
        console.log(error);
        res.send("error");
    }
})

// 查询指定id的意见反馈数据
app.post('/get_advice', async (req, res) => {
    try {
        const { _id } = req.body;
        const result = await Advice.findById(_id);
        res.send(result);
    } catch (error) {
        console.log(error);
        res.send("error");
    }
})

// 上传文件
app.post('/upload_file', upload.array("file", 6), (req, res) => {
    res.send(req.files);
})

// 新增维修订单
app.post('/add_service_order', async (req, res) => {
    const orderNo = await generateOrderNo();
    try {
        const { order_id, user_id, user_info, name, mobile, house, visit_time, fault_type, file_list, fault_desc } = req.body;
        await ServiceOrder.create({
            order_id: orderNo,
            user_id,
            user_info,
            name,
            mobile,
            house,
            visit_time,
            fault_type,
            file_list,
            fault_desc,
            status: 0,
            create_time: new Date().getTime(),
        })
        res.send("success");
    } catch (error) {
        console.log(error);
        res.send("error");
    }
})

// 查询维修订单
app.post('/get_service_order_list', async (req, res) => {
    try {
        const { order_id, user_id, worker_user_id, status, page, size } = req.body;
        if ((user_id || worker_user_id)) {
            let params = {

            };
            if (user_id) {
                params.user_id = user_id;
            } else if (worker_user_id) {
                params.worker_user_id = worker_user_id;
            }

            if (status || status == 0) {

                params.status = status
            }
            const result = await ServiceOrder.find(params);
            res.send({
                result
            })
        } else if (user_id) {
            const result = await ServiceOrder.find({ user_id: user_id });
            res.send({
                result
            })
        } else if (page && size) {
            const result = await ServiceOrder.find().skip((page - 1) * size).limit(size);
            const total = await ServiceOrder.countDocuments();
            res.send({
                result,
                total
            })
        } else {
            res.send("error");
        }

    } catch (error) {
        console.log(error);
        res.send("error");
    }
});
// 后台管理系统登录
app.post('/admin_login', async (req, res) => {
    try {
        const { username, password } = req.body;
        const result = await Admin.findOne({
            username,
            password
        });

        if (result) {
            res.send({
                msg: "success",
                result
            })
        } else {
            res.send({
                msg: "accountError"
            })
        }

    } catch (error) {
        console.log(error);
        res.send({
            msg: "error"
        })
    }
})

// 查询用户列表
app.post('/get_user_list', async (req, res) => {
    try {
        const { role, page, size, keyword } = req.body;

        if (page && size) {

            let params = {
                role
            };

            if (keyword) {
                params.user_id = {
                    $regex: new RegExp(keyword),
                    $options: 'i'
                }
            }

            const result = await User.find(params).skip((page - 1) * size).limit(size);
            const total = await User.countDocuments();
            res.send({
                result,
                total
            })
        } else if (typeof role === 'number') {
            const result = await User.find({
                role
            });

            res.send(result);
        } else {
            res.send("error");
        }
    } catch (error) {
        console.log(error);
        res.send("error");
    }
})

// 分配维修订单
app.post('/assign_service_order', async (req, res) => {
    try {
        const { _id, worker_user_id } = req.body;
        await ServiceOrder.findByIdAndUpdate(_id, {
            worker_user_id,
            status: 1
        });
        res.send("success");
    } catch (error) {
        console.log(error);
        res.send("error");
    }
})

// 删除维修订单
app.post('/delete_service_order', async (req, res) => {
    try {
        const { _id } = req.body;
        await ServiceOrder.findByIdAndDelete(_id);
        res.send("success");
    } catch (error) {
        console.log(error);
        res.send("error");
    }
})

// 查询反馈列表
app.post('/get_advice_all_list', async (req, res) => {
    try {
        const { page, size, role } = req.body;

        const result = await Advice.find({
            role
        }).skip((page - 1) * size).limit(size);
        const total = await Advice.countDocuments();
        res.send({
            result,
            total
        })
    } catch (error) {
        console.log(error);
        res.send("error");
    }
})

// 重新提交未修复好的保修单
app.post('/reassign_order', async (req, res) => {
    try {
        const { _id, user_id } = req.body;

        const order = await ServiceOrder.findOne({ _id, user_id, status: 2 });
        if (!order) {
            return res.send("无效报修单！");
        }

        await ServiceOrder.findByIdAndUpdate(_id, {
            status: 0,
        });
        res.send("success");
    } catch (error) {
        console.log(error);
        res.send("error");
    }
});



//撤销待处理的报修单
app.post('/revoke_order', async (req, res) => {
    try {
        const { _id, user_id } = req.body;
        const order = await ServiceOrder.findOne({
            _id,
            user_id,
            status: 0
        })
        if (!order) {
            return res.send("无效报修单");
        }
        await ServiceOrder.findByIdAndUpdate(_id, {
            status: 3,
        })
        res.send("succes");
    } catch (error) {
        console.log(error)
        res.send("error")
    }

})
//重新提交已修复好的保修单
app.post('/fixed_order', async (req, res) => {
    try {
        const { _id, user_id, order_id } = req.body;
        const params = {
            _id: _id,
            status: 3
        }
        if (user_id) {
            params.user_id = user_id
        }

        const order = await ServiceOrder.findOne(params);
        if (!order) {
            return res.send("无效报修单！");
        }

        const result = await ServiceOrder.findByIdAndUpdate(_id, {
            status: 0,
            worker_user_id: ''
        });
        res.send({
            code: 200,
            msg: "已更改为待维修"
        });


    } catch (error) {
        console.log(error);
        res.send("error");
    }
});



// 处理意见反馈
app.post('/handle_advice_result', async (req, res) => {
    try {
        const { _id, result } = req.body;
        await Advice.findByIdAndUpdate(_id, {
            result,
            status: 1
        });

        res.send("success");
    } catch (error) {
        console.log(error);
        res.send("error");
    }
})

// 删除意见反馈
app.post('/delete_advice', async (req, res) => {
    try {
        const { _id } = req.body;
        await Advice.findByIdAndDelete(_id);

        res.send("success");
    } catch (error) {
        console.log(error);

        res.send("error");
    }
})

// 修改工作人员处理订单的过程
app.post('/update_service_order_info', async (req, res) => {
    try {
        const { _id, start_info, finish_info, status } = req.body;
        let params = {
            status
        };

        if (start_info) {
            params.start_info = start_info;
        } else if (finish_info) {
            params.finish_info = finish_info;
        }
        await ServiceOrder.findByIdAndUpdate(_id, params);

        res.send("success");
    } catch (error) {
        console.log(error);
        res.send("error");
    }
})


createSuperAdmin();

app.listen(3000, () => {
    console.log('后端项目跑起来了，在端口号3000！');
})